﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using boe2.irc;

namespace wpfirc
{
	/// <summary>
	/// Interaction logic for IrcChannelControl.xaml
	/// </summary>
	public partial class IrcChannelControl : UserControl
	{
		public IrcConnection Connection { get; private set; }
		public IrcChannel Channel { get; private set; }

		public IrcChannelControl(IrcConnection connection, IrcChannel channel)
		{
			InitializeComponent();
			Connection = connection;
			Channel = channel;
			DataContext = Channel;
		}
	

		public void SendMessage(IrcMessage message)
		{
			switch (message.MessageType)
			{
				case MessageType.CHANNELTOPIC:
				case MessageType.TOPIC:
					Channel.SetTopic(message.Message);
					break;
				case MessageType.USERLIST:
					foreach (String user in message.Message.Split(' '))
					{
						Channel.AddUser(user);
					}
					break;
				case MessageType.JOIN:
					Channel.AddUser(message.Prefix.Nick);
					break;
				case MessageType.QUIT:
				case MessageType.PART:
					Channel.RemoveUser(message.Prefix.Nick);
					break;
			}
			Channel.AddMessage(message);
		}

        public void SendText(String text)
        {
			AddTextLine(text);
        }

		private void SendContent(object sender, ExecutedRoutedEventArgs e)
		{
			if (inputBox.Text.StartsWith("/"))
			{
		
				Connection.SendCommand(new IrcCommand(inputBox.Text.Substring(1)));
				AddTextLine(inputBox.Text.Substring(1));
			}
			else
			{
				Connection.SendCommand(IrcCommand.CreatePRIVMSG(inputBox.Text, Channel.Name));
				AddLine(new IrcMessage("", Connection.NickName + "!testconsole@127.0.0.1", "PRIVMSG", Channel.Name, inputBox.Text));
			}
			inputBox.Clear();
		}

		private void CanSendContent(object sender, CanExecuteRoutedEventArgs e)
		{
			e.CanExecute = !String.IsNullOrEmpty(inputBox.Text);
		}

		private void AddLine(IrcMessage message)
		{
			Channel.AddMessage(message);
		}

		private void AddTextLine(String text)
		{
			IrcMessage message = new IrcMessage(text, null, "TEXT", null, text);
			Channel.AddMessage(message);
		}
	}
}
